﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.MyLogs;
using B.S.BasicData.Api.Read.Dtos;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.CommandHandler.MyLogs
{
    public class GetLogHandler : IRequestHandler<GetLogCommand, ApiPaging<LogDto>>
    {
        private readonly IBaseRepository<LogModel> logRepo;
        private readonly IMapper mapper;

        public GetLogHandler(IBaseRepository<LogModel> logRepo, IMapper mapper)
        {
            this.logRepo = logRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 查询日志的中介者处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiPaging<LogDto>> Handle(GetLogCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<LogDto> result = new ApiPaging<LogDto>();//实例化一个分页包装响应类

            var logs = logRepo.GetAll();
            if (!string.IsNullOrEmpty(request.UserName))
            {
                logs = logs.Where(x => x.CreateName.Contains(request.UserName));//如果用户名不为空,根据用户名查询
            }

            if (request.CreateTime != null)
            {
                //如果操作时间不为空,根据操作时间过滤数据
                logs = logs.Where(x => x.CreateTime >= request.CreateTime.Value.AddDays(-1) && x.CreateTime <= request.CreateTime.Value.AddDays(1));
            }
            result.TotalCount = logs.Count();//总条数
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);//总页数
            //取分页数据
            var page = logs.OrderByDescending(x => x.Id)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToList();


            result.Items = mapper.Map<List<LogDto>>(page); //把取到的数据转换为分页数据

            result.Code = ApiEnums.Success;
            result.Msg = "分页查询完成!";

            return Task.FromResult(result); 
        }
    }
}
